package pers.brozen.anka.service;

import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import pers.brozen.anka.apis.params.category.AddCategoryParam;
import pers.brozen.anka.apis.params.category.DeleteCategoryParam;
import pers.brozen.anka.apis.vos.CategoryVo;
import pers.brozen.anka.dao.entity.Category;
import pers.brozen.anka.dao.repository.CategoryRepository;
import pers.brozen.anka.support.web.response.ErrorCodes;
import pers.brozen.anka.support.web.response.ResponseException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Brozen
 * @since 2024-05-28
 */
@Service
public class CategoryService {

    @Resource
    private CategoryRepository categoryRepo;


    @Cacheable(cacheNames = "AnkaCache", key = "categories")
    public List<CategoryVo> getCategories() {
        List<Category> categories = categoryRepo.findAll();
        return categories.stream()
                .map(category -> {
                    CategoryVo vo = new CategoryVo();
                    vo.setId(category.getId());
                    vo.setName(category.getName());
                    vo.setDesc(category.getDescription());
                    vo.setIcon(category.getIcon());
                    return vo;
                })
                .collect(Collectors.toList());
    }


    @CacheEvict(cacheNames = "AnkaCache", key = "categories")
    public void addCategory(AddCategoryParam param) {
        categoryRepo.findById(param.getId())
                .ifPresent(_c -> {
                    throw new ResponseException(ErrorCodes.CATEGORY_EXIST);
                });

        Category category = new Category();
        category.setId(param.getId());
        category.setName(param.getName());
        category.setDescription(param.getDesc());
        category.setIcon(param.getIcon());
        categoryRepo.save(category);
        categoryRepo.flush();
    }


    @CacheEvict(cacheNames = "AnkaCache", key = "categories")
    public void deleteCategory(DeleteCategoryParam param) {
        categoryRepo.deleteById(param.getId());
        categoryRepo.flush();
    }

}
